package com.three.db.config;

import com.three.db.annotation.DemoDbRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.*;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

/**
 * Created by ziqingwang on 2017/6/1 0001.
 */
@Configuration
//启动项目配置  db.ordinary或者db.sharding,存在该数据库，才配置
@DataSourceConditional(db_name = {"demo"})
@EnableConfigurationProperties(JpaProperties.class)
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory_demo",
        transactionManagerRef = "transactionManager_demo",
        basePackages ={"com.three.**"}, includeFilters={@ComponentScan.Filter(type = FilterType.ANNOTATION, value = DemoDbRepo.class)}//不指定包，只会扫描当前目录下的包和类
) //设置Repository所在位置
public class DemoJpaConfig {
    private final String dbKey="demo";
    @Autowired
    private JpaProperties jpaProperties;
    @Autowired
    private DataSourceConfig dataSourceConfig;

    @Bean(name="entityManagerFactory_demo")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder,@Qualifier(value = "demoDataSource") DataSource dataSource) {
        return builder
                .dataSource(dataSource)
                .properties(jpaProperties.getHibernateProperties(dataSource))
                .packages("com.three.**") //设置实体类所在位置
                .persistenceUnit("demo")
                .build();
    }

    @Bean(name="transactionManager_demo")
    public PlatformTransactionManager transactionManagerPrimary(@Qualifier(value = "entityManagerFactory_demo") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
    @Bean(name="demoDataSource")
    public DataSource dataSource(){
        return dataSourceConfig.getDataSource(dbKey);
    }
}
